package com.zmn.oms.services.impl.fcorderpart;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.fcorderpart.FcOrderPartCheckDTO;
import com.zmn.oms.model.entity.fcorderpart.FcOrderPartQuery;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPart;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPost;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPostQuery;
import com.zmn.oms.persistence.interfaces.fcorderpart.OrderFactoryPartDao;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：厂商配件服务
 * @author lujia
 * @date 2019/5/10 9:33
 */
@Service
public class OrderFactoryPartServiceImpl implements OrderFactoryPartService {
    private static final Logger logger = LoggerFactory.getLogger(OrderFactoryPartServiceImpl.class);

    @Autowired(required = false)
    private OrderFactoryPartDao orderFactoryPartDao;
    @Autowired(required = false)
    private OrderFactoryPartPostService orderFactoryPartPostService;

    @Override
    public OrderFactoryPart findByKey(Integer fcOrderPartId) {
        return orderFactoryPartDao.findByKey(fcOrderPartId);
    }

    @Override
    public List<OrderFactoryPart> listByIds(List<Integer> ids) {
        return orderFactoryPartDao.listByIds(ids);
    }

    @Override
    public List<OrderFactoryPart> listEsOrderFactoryPartByOrderIdList(List<Long> orderIdList) {
        return orderFactoryPartDao.listEsOrderFactoryPartByOrderIdList(orderIdList);
    }

    @Override
    public List<OrderFactoryPart> listOrderFactoryPartByOrderId(Long orderId) {
        return orderFactoryPartDao.listOrderFactoryPartByOrderId(orderId);
    }

    @Override
    public List<Integer> listIdPartByOrderIdAndApplyType(Long orderId, Integer applyType) {
        return orderFactoryPartDao.listIdPartByOrderIdAndApplyType(orderId, applyType);
    }

    @Override
    public void update(OrderFactoryPart orderFactoryPart) {
        orderFactoryPartDao.update(orderFactoryPart);
    }

    @Override
    public void updateBatch(List<OrderFactoryPart> orderFactoryPart) {
        orderFactoryPartDao.updateBatch(orderFactoryPart);
    }

    @Override
    public int countByOrderId(Long orderId) {
        return orderFactoryPartDao.countByOrderId(orderId);
    }

    @Override
    public void deleteByOrderId(Long orderId) {
        orderFactoryPartDao.deleteByOrderId(orderId);
    }

    @Override
    public void deleteByKey(Integer fcOrderPartId) {
        orderFactoryPartDao.deleteByKey(fcOrderPartId);
    }

    @Override
    public void deleteByFcOrderPartIds(List<Integer> idList) {
        orderFactoryPartDao.deleteByFcOrderPartIds(idList);
    }

    @Override
    public void addFactoryPartList(List<OrderFactoryPart> partList) {
        orderFactoryPartDao.insertAll(partList);
    }

    @Override
    public int addFactoryPart(OrderFactoryPart part) {
        return orderFactoryPartDao.insert(part);
    }

    @Override
    public List<OrderFactoryPart> listByOrderId(Long orderId) {
        List<Long> ids = Lists.newArrayList(orderId);
        List<OrderFactoryPart> partList = orderFactoryPartDao.listEsOrderFactoryPartByOrderIdList(ids);
        return partList;
    }

    @Override
    public List<OrderFactoryPart> listPageByQuery(FcOrderPartQuery fcOrderPartQuery) {
        // 若根据快递单号查询E
        if (StringUtils.isNotBlank(fcOrderPartQuery.getExpressCode())){
            OrderFactoryPartPostQuery query = new OrderFactoryPartPostQuery();
            List<OrderFactoryPartPost> posts = orderFactoryPartPostService.listByExpressCode(fcOrderPartQuery.getExpressCode());
            if (posts.size() > 0){
                List<Integer> orderPartIdList = posts.stream().map(e -> e.getFcOrderPartId()).collect(Collectors.toList());
                fcOrderPartQuery.setFcOrderPartIdList(orderPartIdList);
            } else {
                return new ArrayList<OrderFactoryPart>();
            }
        }
        fcOrderPartQuery.setTotalCount(orderFactoryPartDao.countByQuery(fcOrderPartQuery));

        if (Objects.nonNull(fcOrderPartQuery.getStatus()) || Objects.nonNull(fcOrderPartQuery.getFcOrderPartPostType())) {
            OrderFactoryPartPostQuery query = new OrderFactoryPartPostQuery();
            query.setFactoryId(fcOrderPartQuery.getFactoryId());
            query.setStatus(fcOrderPartQuery.getStatus());
            query.setFcOrderPartPostType(fcOrderPartQuery.getFcOrderPartPostType());
            List<OrderFactoryPartPost> partPosts = orderFactoryPartPostService.listForOrderPart(query);

            if (CollectionUtil.isNullOrEmpty(partPosts)) {
                return Lists.newArrayList();
            }
            fcOrderPartQuery.setFcOrderPartIdList(partPosts.stream().map(OrderFactoryPartPost::getFcOrderPartId).distinct().collect(Collectors.toList()));
        }

        return orderFactoryPartDao.listPageByQuery(fcOrderPartQuery);
    }

    @Override
    public List<OrderFactoryPart> listByQuery(FcOrderPartQuery fcOrderPartQuery) {
        return orderFactoryPartDao.listByQuery(fcOrderPartQuery);
    }

    /**
     * 厂家配件检查
     * @param orderId
     * @return
     */
    @Override
    public FcOrderPartCheckDTO doFactoryPartCheck(Long orderId) throws OmsBaseException {
        FcOrderPartCheckDTO check = new FcOrderPartCheckDTO();

        List<OrderFactoryPart> orderFactoryParts = this.listByOrderId(orderId);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(orderFactoryParts)) {
            // 没有厂商配件信息
            check.setContainsFcPart(false);
            check.setContainsFcPartPost(false);
            check.setContainsWaiting4FcReview(false);
            check.setContainsFcPartWaiting4Post(false);
            check.setNeedReturnFcPart(false);
            check.setContainsReturnFcPartWaiting4Post(false);
            return check;
        }

        check.setContainsFcPart(true);
        check.setOrderFactoryParts(orderFactoryParts);

        // 是否有待厂商审核配件
        for (OrderFactoryPart item : orderFactoryParts) {
            if (Objects.equals(item.getReviewStatus(), OrderConsts.REVIEW_STATUS_DOING)) {
                check.setContainsWaiting4FcReview(true);
            }
        }
        // 获取审核成功配件
        List<OrderFactoryPart> successParts = orderFactoryParts.stream()
                .filter(item -> Objects.equals(item.getReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(successParts)) {
            check.setReviewSuccessParts(successParts);

            // 是否需要旧件返厂
            for (OrderFactoryPart item : successParts) {
                // 厂家审核通过，如果未设置需要旧件返厂，按不需要旧件返厂处理
                if (Objects.equals(item.getRetrieve(), GlobalConsts.YES)) {
                    check.setNeedReturnFcPart(true);
                    break;
                }
            }
        }

        List<OrderFactoryPartPost> orderFactoryPartPosts = orderFactoryPartPostService.listByOrderId(orderId);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(orderFactoryPartPosts)) {
            return check;   // 不包含配件邮寄信息
        }

        check.setContainsFcPartPost(true);
        check.setOrderFactoryPartPosts(orderFactoryPartPosts);
        // 是否有厂家未寄出的配件
        for (OrderFactoryPartPost item : orderFactoryPartPosts) {
            if (Objects.equals(item.getFcOrderPartPostType(), OrderConsts.FACTORY_PART_POST_TYPE_SEND)
                    && (Objects.equals(item.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_WAIT_PROCESS)
                        || Objects.equals(item.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT)) ) {
                check.setContainsFcPartWaiting4Post(true);
                break;
            }
        }
        // 旧件返厂：是否有工程师未寄出的返厂配件
        if (check.isNeedReturnFcPart()) {
            for (OrderFactoryPartPost item : orderFactoryPartPosts) {
                if (Objects.equals(item.getFcOrderPartPostType(), OrderConsts.FACTORY_PART_POST_TYPE_RETURN)
                        && (Objects.equals(item.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_WAIT_PROCESS)
                            || Objects.equals(item.getStatus(), GlobalConsts.EXPRESS_POST_STATUS_WAIT_TRANSIT)) ) {
                    check.setContainsReturnFcPartWaiting4Post(true);
                    break;
                }
            }
        }

        return check;
    }
}
